package com.flash.ticket.utils;

import org.springframework.util.ResourceUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SendMailUtil {

    //发送方邮箱
    private String startEmail = "rws20011128@163.com";
    //邮件服务器密码
    private String startPasssword = "MUVXHOFMRBBKPHFK";
    //邮件接收方
    private String email = "2873823585@qq.com";
    //主题
    private String subjectName = "主题";
    //内容
    private String content = "简单的纯文本邮件，点击 <a href='http://www.baidu.com'>百度</a>";
    //附件数组
    private List<String> filePathList = null;

    public String getStartEmail() {
        return startEmail;
    }

    public void setStartEmail(String startEmail) {
        this.startEmail = startEmail;
    }

    public String getStartPasssword() {
        return startPasssword;
    }

    public void setStartPasssword(String startPasssword) {
        this.startPasssword = startPasssword;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getSubjectName() {
        return subjectName;
    }

    public void setSubjectName(String subjectName) {
        this.subjectName = subjectName;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public List<String> getFilePathList() {
        return filePathList;
    }

    public void setFilePathList(List<String> filePathList) {
        this.filePathList = filePathList;
    }

    public void send(){

        //1、连接邮件服务器的参数配置
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.163.com");

        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //开启debug
        session.setDebug(true);

        Message mimeMessage;
        if(filePathList == null){
            //调用生成邮件内容（普通邮件）
            mimeMessage = getMimeMessage(session);
        }else{
            //调用生成邮件内容（带附件的邮件）
            mimeMessage = getMimeMessageFile(session);
        }

        try{
            //构造一个邮件发送器
            Transport transport = session.getTransport();
            //设置发件人的账户名和密码
            transport.connect(startEmail, startPasssword);
            //发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
            //如果只想发送给指定的人，可以如下写法
            //transport.sendMessage(mimeMessage, new Address[]{new InternetAddress("xxx@qq.com")});
            //5、关闭邮件连接
            transport.close();
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    private MimeMessage getMimeMessage(Session session){
        try {
            //创建一封邮件的实例对象
            MimeMessage mimeMessage = new MimeMessage(session);
            //设置发件邮箱地址
            mimeMessage.setFrom(new InternetAddress(startEmail));
            /**
                    * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
              
                    * MimeMessage.RecipientType.TO:发送
              
                    * MimeMessage.RecipientType.CC：抄送
              
                    * MimeMessage.RecipientType.BCC：密送
              
                    */
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(email));
            //设置邮件主题
            mimeMessage.setSubject(subjectName, "UTF-8");
            //设置邮件正文
            mimeMessage.setContent(content, "text/html;charset=UTF-8");
            //设置邮件的发送时间,默认立即发送
            mimeMessage.setSentDate(new Date());
            return mimeMessage;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private MimeMessage getMimeMessageFile(Session session) {

        try {

            //文件路径
            String path = ResourceUtils.getURL("classpath:static/").getPath();

            //创建一封邮件的实例对象
            MimeMessage mimeMessage = new MimeMessage(session);
            //设置发件邮箱地址
            mimeMessage.setFrom(new InternetAddress(startEmail));
            /**
                    * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
              
                    * MimeMessage.RecipientType.TO:发送
              
                    * MimeMessage.RecipientType.CC：抄送
              
                    * MimeMessage.RecipientType.BCC：密送
              
                    */
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(email));
            //设置邮件主题
            mimeMessage.setSubject(subjectName, "UTF-8");

            /**
             * 开始设置内容文本+附件
             */

            //组合文本+附件（初始化一个容器）
            MimeMultipart mimeMultipart = new MimeMultipart();

            //设置文本
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(content, "text/html;charset=UTF-8");
            mimeMultipart.addBodyPart(text);

            //String[] filePath = {"linuxLogo.png", "学习工作计划+班规.docx"};

            for (String value : filePathList){
                //设置附件
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                //读取本地数据
                DataHandler dataHandler = new DataHandler(new FileDataSource(path + value));
                //附件添加到节点
                mimeBodyPart.setDataHandler(dataHandler);
                //设置附件名称
                mimeBodyPart.setFileName(MimeUtility.encodeText(dataHandler.getName()));
                mimeMultipart.addBodyPart(mimeBodyPart);
            }

            mimeMultipart.setSubType("mixed");

            //设置邮件内容
            mimeMessage.setContent(mimeMultipart);
            //设置邮件的发送时间,默认立即发送
            mimeMessage.setSentDate(new Date());

            return mimeMessage;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        SendMailUtil sendMailUtil = new SendMailUtil();
        //设置收件人邮箱
        sendMailUtil.setEmail("704976433@qq.com");
        //设置邮件标题
        sendMailUtil.setSubjectName("测试邮件的封装工具类");
        //设置内容
        sendMailUtil.setSubjectName("测试邮件的封装工具类-内容");
        //设置附件
        List<String> filePathList = new ArrayList<>();
        filePathList.add("linuxLogo.png");
        filePathList.add("学习工作计划+班规.docx");
        sendMailUtil.setFilePathList(filePathList);
    }

}
